#!/bin/bash
set -x

. /sbin/ramfs.sh
#set +e
# Default PATH differs between shells, and is not automatically exported
export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
export TERM=linux
export HOME=/root
export LANG=zh_CN.UTF-8


[ -d /dev ] || mkdir -m 0755 /dev
[ -d /root ] || mkdir -m 0700 /root
[ -d /sys ] || mkdir /sys
[ -d /proc ] || mkdir /proc
[ -d /run ] || mkdir /run
[ -d /tmp ] || mkdir /tmp
[ -d /var/lock ] || mkdir -p /var/lock
mount -t sysfs -o nodev,noexec,nosuid sysfs /sys
mount -t proc -o nodev,noexec,nosuid proc /proc

# Note that this only becomes /dev on the real filesystem if udev's scripts
# are used; which they will be, but it's worth pointing out
mount -t devtmpfs -o nosuid,mode=0755 udev /dev

[ -d /dev/pts ] || mkdir /dev/pts
mount -t devpts -o noexec,nosuid,gid=5,mode=0620 devpts /dev/pts || true

mount -t tmpfs -o "nodev,noexec,nosuid,size=${RUNSIZE:-10%},mode=0755" tmpfs /run

if [ ! -d /dev/fd ] && [ -d /proc/self/fd ]; then
	ln -s /proc/self/fd /dev/fd
fi

mkdir -p /var/log

load_module virtio_pci
load_module virtio_scsi
load_module nvme
load_module mmc_core
load_module phytium_sdci

echo $(cat /proc/cmdline)
for x in $(cat /proc/cmdline); do
        case "${x}" in
                root=*)
                        root="${x#root=}"
                        break;;
        esac
done

[ -z "${root}" ] && echo "Empty root= argument"

echo "$root"
device=""
case "${root}" in
        LABEL=)
                root="${root#LABEL=}"
                #root="/dev/disk/by-label/${root#LABEL=}"
		device=$(blkid | grep "LABEL=\"${root}"  | awk -F: '{print $1}')
                ;;
        UUID=*)
                root="${root#UUID=}"
		#root="/dev/disk/by-uuid/${root#UUID=}"
		device=$(blkid | grep "UUID=\"${root}"  | awk -F: '{print $1}')
                ;;
        /dev/*)
		device=$root
                ;;
	*)
		root=""
		;;
esac
echo "$root" ${device}

if [ -z "${device}" ]; then
       	echo "Empty root= argument"
	in_ramfs
else
	fsck -a ${device}
	mount ${device} /tmp
	if [ $? != 0  ]; then
		echo "root mount failed"
		in_ramfs
	else
		ls /tmp/
		if [ -f /tmp/sysrecover ]; then
			echo "kernel gen sysrecover"
			rm -f /tmp/sysrecover
			umount /tmp
			in_ramfs
		else
			umount /tmp
		fi
	fi
fi

#mount 
# [ $? = 0 ] || return

#rmmod virtio_scsi
#rmmod virtio_pci
#rmmod nvme
#rmmod mmc_core

umount /run
umount /dev/pts
umount /dev
umount /proc
umount /sys
exec /sbin/init
